# 导入Django的配置信息 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'haoke_mall.settings.dev')
import time
from collections import OrderedDict

import os,sys
#
sys.path.insert(0,'../')
#  添加Django的配置信息
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    #  添加配置信息
    os.environ['DJANGO_SETTINGS_MODULE'] = 'haoke_mall.settings.dev'

# 调用Django模块
import django
django.setup()



from goods.models import SKU, GoodsChannel, Content, ContentCategory
from goods.utils import get_categories
from django.conf import settings
from django.template import loader
# 生成详情页 的数据

def generate_static_index_html():
    """
    生成静态的主页html文件  index.html
    """
    print('%s: generate_static_index_html' % time.ctime())
    # 商品频道及分类菜单
    # 使用有序字典保存类别的顺序
    # categories = {
    #     1: { # 组1
    #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
    #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
    #     },
    #     2: { # 组2
    #
    #     }
    # }
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 手机通讯中的时尚新品
    content_list = []
    # 手机通讯中的畅享低价
    content_list_fl = []
    #  手机配件 数据
    content_list_pj = []
    # 2楼加价换购  16
    content_list_hg = []
    # 2楼畅享低价 18
    content_list_dj = []
    # 3楼生活用品
    content_list_sh = []
    # 3楼厨房用品
    content_list_cf = []
    for channel in channels:
        group_id = channel.group_id  # 当前组

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 当前频道的类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []
            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    # from contents.crons import generate_static_index_html
    category1 = [8, 10, 11, 16, 18, 24, 25]
    for i in category1:
        content = Content.objects.filter(category_id=i)
        # print(content)
        for j in content:
            print(j)
            print(type(j))

            title = j.title
            image = j.image
            category = j.category_id
            # print(title)
            # print(category)
            text = j.text

            content_data = {
                'title': title,
                'image': image,
                'category': category,
                'text': text
            }
            if category == 8:
                content_list.append(content_data)
            # content_list_fl
            elif category == 10:
                content_list_fl.append(content_data)
            # content_list_pj
            elif category == 11:
                content_list_pj.append(content_data)
            # content_list_hg
            elif category == 16:
                content_list_hg.append(content_data)
            # content_list_dj
            elif category == 18:
                content_list_dj.append(content_data)
            # content_list_sh
            elif category == 24:
                content_list_sh.append(content_data)
            # content_list_cf
            elif category == 25:
                content_list_cf.append(content_data)
    print(content_list)
    print(content_list_fl)
    # 广告内容
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    # 广告图片查询
    contents_url = []

    content = Content.objects.filter(category_id=1)
    # print(content)
    for j in content:
        title = j.title
        image = j.image
        category = j.category_id
        # print(title)
        # print(category)
        content_data = {
            'title': title,
            'image': image,
            'category': category
        }
        contents_url.append(content_data)
    # print(contents_url)
    # 渲染模板
    context = {
        'categories': categories,
        'contents': contents,
        'content_data': content_list,
        'contents_url': contents_url,
        'content_list_fl': content_list_fl,
        'content_list_pj': content_list_pj,
        'content_list_hg': content_list_hg,
        'content_list_dj': content_list_dj,
        'content_list_cf': content_list_cf,
        'content_list_sh': content_list_sh,
    }
    #template = loader.get_template('index.html')  # 这个用来渲染数据的文件
    template = loader.get_template('index.html')
    html_text = template.render(context)
    #  指定前端的目录下的index.html
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)

def generate_static_list_html():
    print('%s: generate_static_list_html' % time.ctime())
    # 哎这啥啊，照搬的时候都不看？你是list列表函数执行index？
    categories = get_categories()
    # 渲染模板
    context = {
        'categories': categories,

    }
    template = loader.get_template('list.html')  # 这个用来渲染数据的文件
    html_text = template.render(context)
    #  指定前端的目录下的index.html
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'list.html')

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)

def generate_static_sku_detail_html(sku_id):
    """
    生成静态商品详情页面
    :param sku_id: 商品sku id
    """
    # 商品分类菜单
    categories = get_categories()
    # print(categories)
    # 获取当前sku的信息
    sku = SKU.objects.get(id=sku_id)
    sku.images = sku.skuimage_set.all()

    # 面包屑导航信息中的频道
    goods = sku.goods
    goods.channel = goods.category1.goodschannel_set.all()[0]

    # 构建当前商品的规格键
    sku_specs = sku.skuspecification_set.order_by('spec_id')
    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)

    # 获取当前商品的所有SKU
    skus = goods.sku_set.all()

    # 构建不同规格参数（选项）的sku字典
    # spec_sku_map = {
    #     (规格1参数id, 规格2参数id, 规格3参数id, ...): sku_id,
    #     (规格1参数id, 规格2参数id, 规格3参数id, ...): sku_id,
    #     ...
    # }
    spec_sku_map = {}
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.skuspecification_set.order_by('spec_id')
        # print(s_specs)
        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id
        # print(tuple(key))
    # 获取当前商品的规格信息
    specs = goods.goodsspecification_set.order_by('id')
    # print(specs)
    # 若当前sku的规格信息不完整，则不再继续
    if len(sku_key) < len(specs):
        return
    for index, spec in enumerate(specs):
        # 复制当前sku的规格键
        key = sku_key[:]
        # print(index)  # 0,1,2
        # print(spec)
        # print(key)
        # 该规格的选项
        options = spec.specificationoption_set.all()
        # print(options)
        for option in options:
            # pass
            # 在规格参数sku字典中查找符合当前规格的sku
            # key = option.id
            # print(key)
            # sku_key= option.id
            key[index] = option.id
            # print(option.id)
            # print(key[index])
            # print(tuple(key))
            # print(option.sku_id)

            option.sku_id = spec_sku_map.get(tuple(key))
            # option.sku_id = spec_sku_map.keys()
            print(option.sku_id)
        # print(key[index])
        spec.options = options
    print(spec_sku_map)
    # 渲染模板，生成静态html文件
    context = {
        'categories': categories,
        'goods': goods,
        'specs': specs,
        'sku': sku
    }

    template = loader.get_template('detail.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'goods/'+str(sku_id)+'.html')
    with open(file_path, 'w') as f:
        f.write(html_text)


if __name__ == '__main__':
    skus =  SKU.objects.all()

    for sku in skus:
        generate_static_sku_detail_html(sku.id)
# def generate_static_sku_detail_html(sku_id):
#     """
#     生成静态商品详情页面
#     :param sku_id: 商品sku id
#     """
#     # 商品分类菜单
#     categories = get_categories()
#     # print(categories)
#     # 获取当前sku的信息
#     sku = SKU.objects.get(id=sku_id)
#     sku.images = sku.skuimage_set.all()
#
#     # 面包屑导航信息中的频道
#     goods = sku.goods
#     goods.channel = goods.category1.goodschannel_set.all()[0]
#
#     # 构建当前商品的规格键
#     sku_specs = sku.skuspecification_set.order_by('spec_id')
#     sku_key = []
#     for spec in sku_specs:
#         sku_key.append(spec.option.id)
#
#     # 获取当前商品的所有SKU
#     skus = goods.sku_set.all()
#
#     # 构建不同规格参数（选项）的sku字典
#     # spec_sku_map = {
#     #     (规格1参数id, 规格2参数id, 规格3参数id, ...): sku_id,
#     #     (规格1参数id, 规格2参数id, 规格3参数id, ...): sku_id,
#     #     ...
#     # }
#     spec_sku_map = {}
#     for s in skus:
#         # 获取sku的规格参数
#         s_specs = s.skuspecification_set.order_by('spec_id')
#         # print(s_specs)
#         # 用于形成规格参数-sku字典的键
#         key = []
#         for spec in s_specs:
#             key.append(spec.option.id)
#         # 向规格参数-sku字典添加记录
#         spec_sku_map[tuple(key)] = s.id
#         # print(tuple(key))
#     # 获取当前商品的规格信息
#     specs = goods.goodsspecification_set.order_by('id')
#     # print(specs)
#     # 若当前sku的规格信息不完整，则不再继续
#     if len(sku_key) < len(specs):
#         return
#     for index, spec in enumerate(specs):
#         # 复制当前sku的规格键
#         key = sku_key[:]
#         # print(index)  # 0,1,2
#         # print(spec)
#         # print(key)
#         # 该规格的选项
#         options = spec.specificationoption_set.all()
#         # print(options)
#         for option in options:
#             # pass
#             # 在规格参数sku字典中查找符合当前规格的sku
#             # key = option.id
#             # print(key)
#             # sku_key= option.id
#             key[index] = option.id
#             # print(option.id)
#             # print(key[index])
#             # print(tuple(key))
#             # print(option.sku_id)
#
#             option.sku_id = spec_sku_map.get(tuple(key))
#             # option.sku_id = spec_sku_map.keys()
#             print(option.sku_id)
#         # print(key[index])
#         spec.options = options
#     print(spec_sku_map)
#     # 渲染模板，生成静态html文件
#     context = {
#         'categories': categories,
#         'goods': goods,
#         'specs': specs,
#         'sku': sku
#     }
#
#     template = loader.get_template('detail.html')
#     html_text = template.render(context)
#     file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'goods/'+str(sku_id)+'.html')
#     with open(file_path, 'w') as f:
#         f.write(html_text)
#
#
#
# if __name__ == '__main__':
#     skus =  SKU.objects.all()
# #
#     for sku in skus:
#         generate_static_sku_detail_html(sku.id)

